
const state = {
	cartList:JSON.parse(uni.getStorageSync('cart') || '[]')
}

const mutations = {
	addToCart(state,goods){
		console.log(goods)
		const findResult = state.cartList.find(item => item.goods_id === goods.goods_id)
		console.log(findResult);
		if(!findResult){
			state.cartList.push(goods)
		}else{
			findResult.goods_count++;
		}
		console.log(state.cartList);
		this.commit('cart/saveToStoreage')
	},
	saveToStoreage(state){
		uni.setStorageSync('cart',JSON.stringify(state.cartList))
	},
	
	//更新购物车中商品的勾选状态
	updateGoodState(state,goods){
		const findResult = state.cartList.find(item => item.goods_id === goods.goods_id)
		if(findResult){
			findResult.goods_state = goods.goods_state
		}
		this.commit('cart/saveToStoreage')
	},
	//修改商品的数量
	updateGoodsCount(state,goods){
		const findReslut = state.cartList.find(item => item.goods_id === goods.goods_id);
		if(findReslut){
			findReslut.goods_count = goods.goods_count;
			this.commit('cart/saveToStoreage')
		}
	},
	//删除购物车中的商品
	removeGoodById(state,goods_id){
		state.cartList = state.cartList.filter(item => item.goods_id !== goods_id);
		console.log(state.cartList);
		this.commit('cart/saveToStoreage')
	},
	updateAllGoodsState(state,goods_state){
		state.cartList.forEach(item =>{
			item.goods_state = goods_state
		})
		this.commit('cart/saveToStoreage')
	}
}

const actions = {
	
}

const getters = {
	//购物车中所有商品的数量
	total(state){
		// let c = 0;
		// state.cartList.forEach(item=> c += item.goods_count);
		// return c;
		return state.cartList.reduce((total,item)=> total += item.goods_count,0)
	},
	//购物车中已勾选的商品数量
	checkedCount(state){
		return state.cartList.filter(x => x.goods_state).reduce((total,item) => total += item.goods_count,0)
		// return state.cartList.filter(x => x.goods_state).reduce((prev,current)=>{
		// 	return prev += current.goods_count
		// },0);
	},
	//勾选商品的总价格
	checkedGoodsAmount(state){
		return state.cartList.filter(item => item.goods_state).reduce((prev,current) => prev += current.goods_count * current.goods_price,0).toFixed(2);
	}
}



export default{
	namespaced:true,
	state,
	mutations,
	actions,
	getters
}